import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/components/index/momentCard.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/event/momonEvent.dart';
import 'package:live_music/models/tag_model.dart';
import 'package:live_music/pages/friendList/widget/list_card_friend.dart';
import 'package:live_music/pages/publish/widget/add_tab_page.dart';
import 'package:live_music/pages/publish/widget/friend_card.dart';
import 'package:live_music/pages/publish/widget/topic_card.dart';
import 'package:live_music/services/tagService.dart';
import 'package:live_music/utils/eventBusUtils.dart';

class TabListPublish extends StatefulWidget {
  final int type;
  TabListPublish({Key key, this.type}) : super(key: key);

  @override
  _TabListPublishState createState() => _TabListPublishState();
}

class _TabListPublishState extends State<TabListPublish>
    with AutomaticKeepAliveClientMixin {
  // 下拉刷新控制器
  EasyRefreshController _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  List<TagModel> _tagListModel;
  // 列表数组模型
  int pageNo = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg;
  String keyWord;
  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    getData();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  getData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {
        "pageNo": pageNo,
        "pageSize": pageSize,
        "keyword": keyWord
      };
      Map<String, dynamic> result = await TagService.queryTag(data);
      List<dynamic> tagList = result['body'];
      TagListModel tagListModel = TagListModel.fromJson(tagList);
      setState(() {
        pageNo++;
        hasMore = pageSize == tagListModel.list.length;
        if (replace) {
          _tagListModel = tagListModel.list;
        } else {
          _tagListModel.addAll(tagListModel.list);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    setState(() {
      pageNo = 1;
    });
    await getData(replace: true);
    if (error) {
      setState(() => error = false);
    }
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await getData(replace: false);
    }
    // // 结束加载
    _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double screeHeight = MediaQuery.of(context).size.height;
    return Container(
      margin:
          EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top),
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text("选择标签"),
          centerTitle: true,
          actions: [
            IconButton(
              icon: Icon(
                Icons.add,
                size: WcaoTheme.fsBase * 1.6,
                color: WcaoTheme.base,
              ),
              onPressed: () async {
                Get.off(AddTabPage());
              },
            )
          ],
        ),
        body: Column(children: [
          search(),
          Container(
              padding:
                  EdgeInsets.only(top: 20, bottom: 20, left: 24, right: 24),
              height: screeHeight - kToolbarHeight - 104,
              child: EasyRefresh(
                  firstRefresh: true,
                  firstRefreshWidget: PageFeedBack(firstRefresh: true).build(),
                  emptyWidget: PageFeedBack(
                    loading: loading,
                    error: error,
                    empty: false,
                    errorMsg: errorMsg,
                    onErrorTap: () => _easyRefreshController.callRefresh(),
                    onEmptyTap: () => _easyRefreshController.callRefresh(),
                  ).build(),
                  header: ClassicalHeader(),
                  footer: ClassicalFooter(),
                  controller: _easyRefreshController,
                  enableControlFinishRefresh: false,
                  enableControlFinishLoad: true,
                  onRefresh: _onRefresh,
                  onLoad: _onLoad,
                  child: ListView.builder(
                      controller: _scrollController,
                      itemCount: _tagListModel.length,
                      itemBuilder: (BuildContext context, int index) {
                        return _buildTabItem(tagItem: _tagListModel[index]);
                      })))
        ]),
      ),
    );
  }

  Widget _buildTabItem({TagModel tagItem}) {
    return InkWell(
      onTap: () {
        EventBusUtils.getInstance().fire(AddTagEvent(tagItem));
        Get.back();
      },
      child: Container(
        padding: EdgeInsets.only(top: 10, bottom: 10, left: 16, right: 16),
        child: Text(tagItem.name),
      ),
    );
  }

  Container search() {
    return Container(
      margin: const EdgeInsets.only(top: 12),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      height: 36,
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(24),
          color: WcaoTheme.bgColor,
        ),
        child: TextField(
          onChanged: (val) {
            setState(() {
              keyWord = val;
            });
          },
          onSubmitted: (val) {
            setState(() {
              keyWord = val;
            });
            _onRefresh();
          },
          enableSuggestions: false,
          autocorrect: false,
          style: TextStyle(fontSize: WcaoTheme.fsBase),
          decoration: const InputDecoration(
            hintText: "请输入搜索关键词",
            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 16),
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
